﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HCFramework.API.LINQ;

namespace C
{
    public class ProductPropertyValueController
    {
        public static void Insert(ProductPropertyValue a)
        {
            // Khong insert neu da ton tai
            if (Get(a.ProductID, a.ProductPropertyID) != null) return;

            HCDataContext db = new HCDataContext();
            db.ProductPropertyValues.InsertOnSubmit(a);
            db.SubmitChanges();
        }

        public static void Update(ProductPropertyValue a, HCDataContext db)
        {
            db.SubmitChanges();
        }

        public static void Delete(int id)
        {
            HCDataContext db = new HCDataContext();
            ProductPropertyValue a = db.ProductPropertyValues.Where(
                ik => ik.ProductPropertyValueID == id).First();
            db.ProductPropertyValues.DeleteOnSubmit(a);
            db.SubmitChanges();
        }

        public static ProductPropertyValue GetByID(int id, HCDataContext db)
        {
            return db.ProductPropertyValues.Where(
                ik => ik.ProductPropertyValueID == id).FirstOrDefault();
        }

        public static ProductPropertyValue GetByID(int id)
        {
            return GetByID(id, new HCDataContext());
        }

        public static ProductPropertyValue Get(int productID, int propertyID)
        {
            return new HCDataContext().ProductPropertyValues.Where(ik =>
                ik.ProductID == productID
                && ik.ProductPropertyID == propertyID).FirstOrDefault();
        }

        public static ProductPropertyValue Get(int productID, int propertyID, HCDataContext db)
        {
            return db.ProductPropertyValues.Where(ik =>
                ik.ProductID == productID
                && ik.ProductPropertyID == propertyID).FirstOrDefault();
        }

        internal static ProductPropertyValue GetOrInsert(int productId, int propertyID, HCDataContext db)
        {
            ProductPropertyValue ppv = Get(productId, propertyID, db);
            if (ppv != null) return ppv;

            ppv = new ProductPropertyValue();
            ppv.ProductID = productId;
            ppv.ProductPropertyID = propertyID;
            ppv.Value = "";
            Insert(ppv);
            return Get(productId, propertyID, db);
        }
    }
}